package cn.yunbamboos.mybatis.mapping.methods.insert;

import cn.yunbamboos.mybatis.mapping.methods.BaseMethod;
import cn.yunbamboos.mybatis.metadata.TableInfo;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;

import java.util.ArrayList;
import java.util.List;


public class Insert extends BaseMethod {

    public Insert(Configuration configuration, TableInfo tableInfo) {
        super("insert", configuration, tableInfo, SqlCommandType.INSERT);
    }

    @Override
    protected SqlSource getSqlSource() {
        String tableName = BACKTICK + this.tableInfo.getTableName() + BACKTICK;
        List<String> columns = new ArrayList<>();
        List<String> values = new ArrayList<>();

        this.tableInfo.getPrimaryKeyList().forEach(pk -> {
            columns.add(BACKTICK + pk.getColumn() + BACKTICK);
            values.add(HASH_LEFT_BRACE + pk.getProperty() + RIGHT_BRACE);
        });

        this.tableInfo.getFieldList().forEach(field -> {
            columns.add(BACKTICK + field.getColumn() + BACKTICK);
            values.add(HASH_LEFT_BRACE + field.getProperty() + RIGHT_BRACE);
        });

        String sql = INSERT(tableName, columns, values);

        return new RawSqlSource(configuration, sql, this.tableInfo.getEntityType());
    }

}
